﻿using MoviesRoom.Data;
using MoviesRoom.ViewModels.Model;
using System;
using System.Linq;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;

namespace MoviesRoom.Controllers
{
    [Authorize]
    public class VotesController : BaseController
    {
        public VotesController() : base(new UowData())
        {
        }

        public VotesController(IUowData data) : base(data)
        {
        }

        //
        // GET: /Vote/
        public ActionResult Vote(VoteModel vote)
        {
            if (ModelState.IsValid)
            {
                var entity = vote.CreateVote();
                var userId = User.Identity.GetUserId();
                entity.UserId = userId;
                
                var film = this.Data.Films.GetById(vote.FilmId);

                if (film.Votes.Any(v => v.UserId == userId))
                {
                    return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "You are already vote for this film");
                }

                if (film != null)
                {
                    film.Votes.Add(entity);
                    this.Data.SaveChanges();

                    return Content((film.Votes.Sum(v => v.Value) / film.Votes.Count()).ToString(), "application/json");
                }
                else
                {
                    return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Invalid film Id");
                }
            }
            else
            { 
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Invalid Vote");
            }
        }
    }
}